﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WebHttpApi.WebHttpApi.Core;
using WebHttpApi.WebHttpApi.HttpApi;

namespace WebHttpApi
{
    /// <summary>
    /// TYGetMeterData 的摘要说明：第三方数据请求接口（数据监控）
    /// </summary>
    public class TYGetMeterData : IHttpHandler
    {
        string str_result = "";

        public void ProcessRequest(HttpContext context)
        {
            //application/json方式：即为JSON数据，不需要检查
            context.Response.ContentType = "application/json";

            //请求主体：JSON格式字符串
            string UserName = "";
            string PassWord = "";
            string MeterIdList = "";
            string Departmentid = "";

            Stream postData = context.Request.InputStream;
            if (postData.Length != 0)
            {
                StreamReader sRead = new StreamReader(postData);
                string postContent = sRead.ReadToEnd();

                sRead.Close();
                JObject json_post = (JObject)JsonConvert.DeserializeObject(postContent);

                UserName = json_post["UserName"].ToString();
                PassWord = json_post["PassWord"].ToString();

                if (SelectIn(UserName, PassWord))
                {
                    MeterIdList = json_post["MeterIdList"].ToString();
                    JArray MeterId = (JArray)JsonConvert.DeserializeObject(MeterIdList);
                    string sql_MeterId = "";
                    for (int i = 0; i < MeterId.Count; i++)
                    {
                        if (sql_MeterId == "")
                        {
                            sql_MeterId = "('" + MeterId[i] + "'";
                        }
                        else
                        {
                            sql_MeterId += ",'" + MeterId[i] + "'";
                        }

                        if (i == MeterId.Count - 1)
                        {
                            sql_MeterId += ",'" + MeterId[i] + "')";
                        }
                    }

                    var MeterDataList = new ArrayList();
                    string sql = "";
                 
                    if (UserName == "tykj"&&PassWord=="tykj@2017")
                    {
                        sql = "select ybdz,xylx,zxlj,zxss,fxlj,fxss,txsj,fmzt,ybdy,sbdy,xhqz,gdyl from v_jk_yz_info where ybdz in ";
                        sql += sql_MeterId;
                    }
                    else
                    {
                        Departmentid = TYMeter.DepartmentId(UserName, PassWord);

                        sql = "select ybdz,xylx,zxlj,zxss,fxlj,fxss,txsj,fmzt,ybdy,sbdy,xhqz,gdyl from v_jk_yz_info where ybdz in ";
                        sql += sql_MeterId + " and DepartmentId like";
                        sql += "'" + Departmentid + "%'";
                    }

                    System.Data.DataTable Meter_Data = WebSdkCore.select(sql);

                    string ybdz = "";
                    string xylx = "";
                    string zxlj = "";
                    string zxss = "";
                    string fxlj = "";
                    string fxss = "";
                    string txsj = "";
                    string fmzt = "";
                    string meter_fm = "";
                    string ybdy = "";
                    string sbdy = "";
                    string meter_dy = "";
                    string xhqd = "";
                    string gdyl = "";

                    if (Meter_Data.Rows.Count > 0)
                    {
                        for (int i = 0; i < Meter_Data.Rows.Count; i++)
                        {
                            ybdz = Meter_Data.Rows[i]["ybdz"].ToString();
                            xylx = Meter_Data.Rows[i]["xylx"].ToString();
                            zxlj = Meter_Data.Rows[i]["zxlj"].ToString();
                            


                            if (xylx == "0" ||
                                xylx == "1" ||
                                xylx == "2" ||
                                xylx == "3" ||
                                xylx == "4" ||
                                xylx == "5" ||
                                xylx == "6" ||
                                xylx == "7" ||
                                xylx == "8" ||
                                xylx == "9" ||
                                xylx == "10" ||
                                xylx == "11" ||
                                xylx == "12" ||
                                xylx == "51" ||
                                xylx == "52" ||
                                xylx == "53")
                            {
                                zxss = "";
                                fxlj = "";
                                fxss = "";
                            }
                            else
                            {
                                zxss = Meter_Data.Rows[i]["zxss"].ToString();
                                fxlj = Meter_Data.Rows[i]["fxlj"].ToString();
                                fxss = Meter_Data.Rows[i]["fxss"].ToString();
                            }

                            txsj = Meter_Data.Rows[i]["txsj"].ToString();
                            fmzt = Meter_Data.Rows[i]["fmzt"].ToString();
                            if (fmzt == "阀开" || fmzt == "Open")
                            {
                                meter_fm = "1";
                            }
                            else if (fmzt == "阀关" || fmzt == "Close")
                            {
                                meter_fm = "0";
                            }
                            else
                            {
                                meter_fm = "2";
                            }

                            ybdy = Meter_Data.Rows[i]["ybdy"].ToString();
                            if (ybdy == "0"||ybdy=="")
                            {
                                sbdy = Meter_Data.Rows[i]["sbdy"].ToString();
                                if (sbdy == "0")
                                {
                                    sbdy = "";
                                }
                                else
                                {
                                    meter_dy = sbdy;
                                }
                            }
                            else
                            {
                                meter_dy = ybdy;
                            }

                            xhqd = Meter_Data.Rows[i]["xhqz"].ToString();
                            gdyl = Meter_Data.Rows[i]["gdyl"].ToString();
                            MeterDataList.Add(new
                            {
                                MeterId = ybdz,
                                PositiveCumulativeFlow = zxlj,
                                PositiveInstantaneousFlow = zxss,
                                AntiCumulativeFlow = fxlj,
                                AntiInstantaneousFlow = fxss,
                                CommunicationTime = txsj,
                                ValveStatus = meter_fm,
                                MeterVoltage = meter_dy,
                                SignalIntensity = xhqd,
                                PipelinePressure=gdyl,
                            }
                            );
                        };
                        var json_result = new
                        {
                            status = "success",
                            MeterDataList = MeterDataList,
                        };
                        str_result = WebSdkCore.ToJSON(json_result);
                    }
                    else
                    {
                        var json_result = new
                        {
                            status = "false",
                            message = "未查询到数据，检查用户账号密码及设备地址",
                        };
                        str_result = WebSdkCore.ToJSON(json_result);
                    }
                }
                else
                {
                    var json_result = new
                    {
                        status = "error",
                        message = "Missing parameter",
                    };
                    str_result = WebSdkCore.ToJSON(json_result);
                }
            }
            else
            {
                var json_result = new
                {
                    status = "error",
                    message = "Missing parameter",
                };
                str_result = WebSdkCore.ToJSON(json_result);
            }
            context.Response.Write(str_result);
        }

        public static bool SelectIn(string UserName, string PassWord)
        {
            bool result;
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))
            {
                result = false;
            }
            else
            {
                result = true;
            }
            return result;
        }   
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}